<template>
  <div class="auth-container">
    <div class="container py-5">
      <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
          <div class="auth-card">
            <!-- 切换按钮 -->
            <div class="auth-toggle mb-4">
              <button 
                :class="['toggle-btn', { active: mode === 'login' }]"
                @click="switchMode('login')"
              >
                登录
              </button>
              <button 
                :class="['toggle-btn', { active: mode === 'register' }]"
                @click="switchMode('register')"
              >
                注册
              </button>
            </div>

            <!-- 登录表单 -->
            <form v-if="mode === 'login'" @submit.prevent="handleLogin" class="auth-form">
              <h3 class="auth-title">用户登录</h3>
              <p class="auth-subtitle">欢迎回到流浪动物之家</p>

              <div class="form-group">
                <label for="loginUsername">用户名</label>
                <input
                  id="loginUsername"
                  v-model="loginForm.username"
                  type="text"
                  class="form-control"
                  placeholder="请输入用户名"
                  required
                />
              </div>

              <div class="form-group">
                <label for="loginPassword">密码</label>
                <input
                  id="loginPassword"
                  v-model="loginForm.password"
                  type="password"
                  class="form-control"
                  placeholder="请输入密码"
                  required
                />
              </div>

              <div class="form-group form-check">
                <input
                  id="rememberMe"
                  v-model="loginForm.rememberMe"
                  type="checkbox"
                  class="form-check-input"
                />
                <label class="form-check-label" for="rememberMe">
                  记住我
                </label>
              </div>

              <button type="submit" class="btn btn-primary btn-auth" :disabled="loginLoading">
                <span v-if="loginLoading" class="spinner-border spinner-border-sm me-2"></span>
                登录
              </button>
            </form>

            <!-- 注册表单 -->
            <form v-else @submit.prevent="handleRegister" class="auth-form">
              <h3 class="auth-title">用户注册</h3>
              <p class="auth-subtitle">加入我们，一起帮助流浪动物</p>

              <div class="form-group">
                <label for="registerUsername">用户名</label>
                <input
                  id="registerUsername"
                  v-model="registerForm.username"
                  type="text"
                  class="form-control"
                  placeholder="请输入用户名（至少3个字符）"
                  required
                  minlength="3"
                />
              </div>

              <div class="form-group">
                <label for="registerNickname">昵称</label>
                <input
                  id="registerNickname"
                  v-model="registerForm.nickname"
                  type="text"
                  class="form-control"
                  placeholder="请输入昵称（可选）"
                />
              </div>

              <div class="form-group">
                <label for="registerEmail">邮箱</label>
                <input
                  id="registerEmail"
                  v-model="registerForm.email"
                  type="email"
                  class="form-control"
                  placeholder="请输入邮箱（可选）"
                />
              </div>

              <div class="form-group">
                <label for="registerPassword">密码</label>
                <input
                  id="registerPassword"
                  v-model="registerForm.password"
                  type="password"
                  class="form-control"
                  placeholder="请输入密码（至少6个字符）"
                  required
                  minlength="6"
                />
              </div>

              <div class="form-group">
                <label for="confirmPassword">确认密码</label>
                <input
                  id="confirmPassword"
                  v-model="registerForm.confirmPassword"
                  type="password"
                  class="form-control"
                  placeholder="请再次输入密码"
                  required
                />
              </div>

              <div class="form-group form-check">
                <input
                  id="agreeTerms"
                  v-model="registerForm.agreeTerms"
                  type="checkbox"
                  class="form-check-input"
                  required
                />
                <label class="form-check-label" for="agreeTerms">
                  我同意《用户协议》和《隐私政策》
                </label>
              </div>

              <button type="submit" class="btn btn-primary btn-auth" :disabled="registerLoading">
                <span v-if="registerLoading" class="spinner-border spinner-border-sm me-2"></span>
                注册
              </button>
            </form>

            <!-- 消息提示 -->
            <div v-if="message.text" :class="['alert', `alert-${message.type}`, 'mt-3']" role="alert">
              {{ message.text }}
            </div>

            <!-- 已有用户提示 -->
            <div class="existing-users mt-4" v-if="existingUsers.length > 0">
              <h6>已注册用户（测试用）：</h6>
              <div class="user-list">
                <div v-for="user in existingUsers" :key="user.id" class="user-item">
                  <span>{{ user.username }}</span>
                  <button 
                    class="btn btn-sm btn-outline-primary"
                    @click="quickLogin(user.username, 'password123')"
                  >
                    快速登录
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import authService from '@/services/auth'

export default {
  name: 'LoginRegister',
  data() {
    return {
      mode: 'login', // 'login' 或 'register'
      loginLoading: false,
      registerLoading: false,
      message: {
        text: '',
        type: 'success' // 'success' 或 'danger'
      },
      loginForm: {
        username: '',
        password: '',
        rememberMe: false
      },
      registerForm: {
        username: '',
        nickname: '',
        email: '',
        password: '',
        confirmPassword: '',
        agreeTerms: false
      }
    }
  },
  computed: {
    existingUsers() {
      return authService.getUsers().slice(0, 3) // 只显示前3个用户
    }
  },
  methods: {
    switchMode(mode) {
      this.mode = mode
      this.clearMessage()
      this.resetForms()
    },
    
    clearMessage() {
      this.message.text = ''
    },
    
    showMessage(text, type = 'success') {
      this.message.text = text
      this.message.type = type
      // 3秒后自动清除消息
      setTimeout(() => {
        this.clearMessage()
      }, 3000)
    },
    
    resetForms() {
      this.loginForm = {
        username: '',
        password: '',
        rememberMe: false
      }
      this.registerForm = {
        username: '',
        nickname: '',
        email: '',
        password: '',
        confirmPassword: '',
        agreeTerms: false
      }
    },
    
    handleLogin() {
      this.loginLoading = true
      this.clearMessage()
      
      // 模拟网络延迟
      setTimeout(() => {
        const result = authService.login(this.loginForm.username, this.loginForm.password)
        
        if (result.success) {
          this.showMessage(result.message, 'success')
          // 登录成功，跳转到首页
          setTimeout(() => {
            this.$router.push('/')
          }, 1000)
        } else {
          this.showMessage(result.message, 'danger')
        }
        
        this.loginLoading = false
      }, 500)
    },
    
    handleRegister() {
      this.registerLoading = true
      this.clearMessage()
      
      // 验证密码确认
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.showMessage('两次输入的密码不一致', 'danger')
        this.registerLoading = false
        return
      }
      
      // 模拟网络延迟
      setTimeout(() => {
        const result = authService.register({
          username: this.registerForm.username,
          nickname: this.registerForm.nickname,
          email: this.registerForm.email,
          password: this.registerForm.password
        })
        
        if (result.success) {
          this.showMessage(result.message, 'success')
          // 注册成功，切换到登录模式
          setTimeout(() => {
            this.switchMode('login')
            this.loginForm.username = this.registerForm.username
          }, 1000)
        } else {
          this.showMessage(result.message, 'danger')
        }
        
        this.registerLoading = false
      }, 500)
    },
    
    quickLogin(username, password) {
      this.loginForm.username = username
      this.loginForm.password = password
      this.handleLogin()
    }
  },
  mounted() {
    // 如果已经登录，直接跳转到首页
    if (authService.isLoggedIn()) {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
.auth-container {
  min-height: 80vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 0;
}

.auth-card {
  background: white;
  border-radius: 15px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
}

.auth-toggle {
  display: flex;
  border-radius: 25px;
  background: #f8f9fa;
  padding: 4px;
  margin-bottom: 30px;
}

.toggle-btn {
  flex: 1;
  padding: 12px;
  border: none;
  background: transparent;
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  color: #666;
}

.toggle-btn.active {
  background: #04A07B;
  color: white;
  box-shadow: 0 4px 15px rgba(4, 160, 123, 0.3);
}

.auth-title {
  color: #333;
  font-weight: 600;
  margin-bottom: 10px;
  text-align: center;
}

.auth-subtitle {
  color: #666;
  text-align: center;
  margin-bottom: 30px;
  font-size: 14px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  color: #333;
  font-weight: 500;
  margin-bottom: 8px;
  display: block;
}

.form-control {
  border: 2px solid #e9ecef;
  border-radius: 10px;
  padding: 12px 15px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.form-control:focus {
  border-color: #04A07B;
  box-shadow: 0 0 0 0.2rem rgba(4, 160, 123, 0.25);
}

.form-check {
  margin-bottom: 25px;
}

.form-check-input {
  margin-top: 4px;
}

.form-check-label {
  color: #666;
  font-size: 14px;
  margin-left: 8px;
}

.btn-auth {
  width: 100%;
  padding: 12px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-auth:disabled {
  opacity: 0.7;
}

.alert {
  border-radius: 10px;
  border: none;
  font-size: 14px;
}

.alert-success {
  background-color: #d4edda;
  color: #155724;
}

.alert-danger {
  background-color: #f8d7da;
  color: #721c24;
}

.existing-users {
  border-top: 1px solid #e9ecef;
  padding-top: 20px;
}

.existing-users h6 {
  color: #666;
  font-size: 14px;
  margin-bottom: 15px;
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 8px;
  font-size: 14px;
}

.user-item span {
  color: #333;
  font-weight: 500;
}

.spinner-border-sm {
  width: 1rem;
  height: 1rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auth-container {
    padding: 20px 0;
  }
  
  .auth-card {
    padding: 30px 20px;
    margin: 0 15px;
  }
  
  .container {
    padding: 0 15px;
  }
}
</style>
